package oldtest;

import gui.*;

import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.util.Iterator;

import javax.swing.JRadioButtonMenuItem;

import boardgame.Board;

import gui.GListener;

public class SwitchAIListener extends GListener {
	
	private TicTac aiMove = null;
	
	public SwitchAIListener(BoardGUI gui, Board board){
		super(gui, board);
	}
	
	protected String updateModel(ActionEvent e) {
		if (e.getSource().getClass() != JRadioButtonMenuItem.class)
			return "Error: Not JRadioButtonMenuItem Class";
		JRadioButtonMenuItem temp = (JRadioButtonMenuItem)e.getSource();		
		try {
			System.out.println(temp.getText());
			if (temp.getText().equals("1 Player")) {
				((TicTacToeTest)board).setAI(true);
				aiMove = (TicTac)((TicTacToeTest)board).moveByAI();				
				System.out.println(aiMove.getPosition()[0]);
				System.out.println(aiMove.getPosition()[1]);
				((TicTacToeTest)board).placePiece(aiMove);
			}
			else 
				((TicTacToeTest)board).setAI(false);			
			return "";
		} catch (Exception ex){
			return ex.toString(); 
		}			
	}

	protected void updateGUI(ActionEvent e, String valid) {
		if (e.getSource().getClass() != JRadioButtonMenuItem.class)
			return;
		if (((JRadioButtonMenuItem)e.getSource()).getText().equals("2 Players"))
			return;
		if (valid.equals("")){			
			if (board.gameEnd()){				
				updateButton();
				gui.clear(board.getWinner());
			} else {
				updateButton();
				System.out.println(board.getCurrentPlayer());
			}
		} else {
			gui.updateStatus(valid);
		}
	}
	
	private void updateButton(){
		Iterator<GButton> it = ((TicTacToeGUITest)gui).buttonGrid.iterator();
		while(it.hasNext()){
			GButton but = it.next();
			if (but.getID()[0]==aiMove.getPosition()[0]&&but.getID()[1]==aiMove.getPosition()[1]){
				gui.update(but);
				break;
			}
		}
	}
	
	protected String updateModel(ItemEvent e) {
		return null;
		// TODO Auto-generated method stub
		
	}
	
	protected void updateGUI(ItemEvent e, String valid) {
		// TODO Auto-generated method stub
		
	}

}
